<?php
class createAdminTask extends sfBaseTask {

  protected function configure() {
    $this->namespace = 'stn';
    $this->name = 'create-admin';
    $this->addOption('env', null, sfCommandOption::PARAMETER_OPTIONAL, 'Changes the environment this task is run in', 'dev');
    $this->addOption('application', null, sfCommandOption::PARAMETER_OPTIONAL, 'Changes the application this task is run in', 'frontend');
    $this->addOption('first-name', null, sfCommandOption::PARAMETER_OPTIONAL, 'First Name', 'frontend');
    $this->addOption('last-name', null, sfCommandOption::PARAMETER_OPTIONAL, 'Last Name', 'frontend');
    $this->addOption('username', null, sfCommandOption::PARAMETER_OPTIONAL, 'Username', 'frontend');
    $this->addOption('email', null, sfCommandOption::PARAMETER_OPTIONAL, 'Email', 'frontend');
    $this->addOption('password', null, sfCommandOption::PARAMETER_OPTIONAL, 'Password', 'frontend');
  }

  protected function execute($arguments = array(), $options = array()) {
    $configuration = ProjectConfiguration::getApplicationConfiguration($options['application'], $options['env'], false);
    sfContext::createInstance($configuration);
    $databaseManager = new sfDatabaseManager($configuration);

    if ($options['first-name'] && $options['last-name'] && $options['username'] && $options['email'] && $options['password']) {
      try {
        $user = new USER();
        $user->setFirstName($options['first-name']);
        $user->setLastName($options['last-name']);
        $user->setUsername($options['username']);
        $user->setEmail($options['email']);
        $salt = StringUtil::generateRandomString(20);
        $user->setSalt($salt);
        $password = StringUtil::hashPassword(trim($options['password']), $salt);
        $user->setPassword($password);
        $user->setUserGroupId(Constants::USER_GROUP_SUPER_ADMIN);
        $user->setType(Constants::USER_TYPE_BASIC_ACCOUNT);
        $user->setStatus(Constants::STATUS_ACTIVE);
        $user->save();
        echo "User created!\n";
      } catch (Exception $e) {
        echo "Unable to create user: " . $e->getMessage() . "\n";
      }
    }
  }
}
?>